//
//  ImageCollectionLayoutCalculator.m
//  WeChatMoments
//
//  Created by Jiang on 2019/8/26.
//  Copyright © 2019 SilverFruity. All rights reserved.
//

#import "ImageCollectionLayoutCalculator.h"

@implementation ImageCollectionLayoutCalculator
- (instancetype)initWithItemCount:(NSInteger)itemCount cellMargin:(CGFloat)cellMargin singleItemViewMaxWidth:(CGFloat)singleItemViewMaxWidth fourItemViewMaxWidth:(CGFloat)fourItemViewMaxWidth nineItemViewMaxWidth:(CGFloat)nineItemViewMaxWidth {
    self = [super init];
    if (self) {
        self.itemCount = itemCount;
        self.cellMargin = cellMargin;
        self.singleItemViewMaxWidth = singleItemViewMaxWidth;
        self.fourItemViewMaxWidth = fourItemViewMaxWidth;
        self.nineItemViewMaxWidth = nineItemViewMaxWidth;
    }
    return self;
}

+ (instancetype)calculatorWithItemCount:(NSInteger)itemCount cellMargin:(CGFloat)cellMargin singleItemViewMaxWidth:(CGFloat)singleItemViewMaxWidth fourItemViewMaxWidth:(CGFloat)fourItemViewMaxWidth nineItemViewMaxWidth:(CGFloat)nineItemViewMaxWidth {
    return [[self alloc] initWithItemCount:itemCount cellMargin:cellMargin singleItemViewMaxWidth:singleItemViewMaxWidth fourItemViewMaxWidth:fourItemViewMaxWidth nineItemViewMaxWidth:nineItemViewMaxWidth];
}
- (NSInteger)rowCount{
    return (self.itemCount - 1) / self.columnCount + 1;
}
- (NSInteger)columnCount{
    if (self.itemCount <= 1)
        return 1;
    else if (self.itemCount > 1 && self.itemCount <= 4)
        return 2;
    else if (self.itemCount <= 9)
        return 3;
    return 0;
}
- (CGFloat)viewWidth{
    if (self.itemCount <= 1)
        return self.singleItemViewMaxWidth;
    else if (self.itemCount > 1 && self.itemCount <= 4)
        return self.fourItemViewMaxWidth;
    else if (self.itemCount <= 9)
        return self.nineItemViewMaxWidth;
    return 0;
}
- (CGSize)itemSize{
    CGFloat itemWidth = (self.viewWidth - (self.columnCount - 1) * self.cellMargin) / self.columnCount;
    return CGSizeMake(itemWidth, itemWidth);
}
- (CGFloat)viewHeight{
    if (self.itemCount == 0) return 1;
    return self.rowCount * self.itemSize.height + (self.rowCount - 1) * self.cellMargin;
}
@end
